<?php

namespace App\Models\Common;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class RedisTool extends Model
{

    /**
     * jsapi signature
     * @param $timestamp
     * @param $nonceStr
     * @param $url
     * @return string
     */
    public static function getSignature($timestamp, $nonceStr, $url)
    {
        $jsapi_ticket = self::getJsApiTicket();
        $string1 = 'jsapi_ticket=' . $jsapi_ticket . '&noncestr=' . $nonceStr . '&timestamp=' . $timestamp . '&url=' .$url;
        return sha1($string1);
    }


    /**
     * 获取jsapi_ticket
     * @return string
     */
    protected static function getJsApiTicket()
    {

        try {
            $jsapi_token = Redis::get('jsapi_token');
            if($jsapi_token){
                return $jsapi_token;
            }else{
                $result = self::refreshJsApiTicket();
                Redis::setex('jsapi_token', $result['expires_in'], $result['ticket']);
                return $result['ticket'];
            }
        } catch (\Exception $e) {
            //如果redis挂掉，放弃请求
            Log::error(RedisTool::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            $result = self::refreshJsApiTicket();
            return $result['ticket'];
        }

    }

    /**
     * 刷新jsapi_ticket
     * @return array
     */
    protected static function refreshJsApiTicket()
    {
        $app = app('wechat.official_account');
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $app->access_token->getToken()['access_token'] . "&type=jsapi";
        $content = file_get_contents($url);
        $result = json_decode($content, true);
        return $result;
    }


    public static function refreshUser($we_id)
    {
        $userInfo = DB::table('lottery_users')->where('we_id',$we_id)->first();
        $userInfo = json_decode(json_encode($userInfo), true);
        Redis::hset('lottery_user_'.$we_id,'userInfo',json_encode($userInfo));
        Redis::hset('lottery_user_'.$we_id,'nickname',$userInfo['nickname']);
        Redis::hset('lottery_user_'.$we_id,'openid',$userInfo['openid']);
        Redis::expire('lottery_user_'.$we_id,7200);
        return $userInfo;
    }

}
